﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.Composition;
using UnfriendlyFire.Models;

namespace UnfriendlyFire.Controllers
{
    [Export(typeof(IController))]
    [ExportMetadata("Name", "Setup")]
    [PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
    public class SetupController : Controller
    {
        private GameRepository _repository;

        [ImportingConstructor]
        public SetupController(GameRepository repository)
        {
            _repository = repository;
        }

        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult Edit()
        {
            Officer existingOfficer = _repository.Officers.Include("Rank").First(o => o.Email == HttpContext.User.Identity.Name);
            return View(existingOfficer);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Edit(Officer officer)
        {
            if (!ModelState.IsValid)
            {
                return View(officer);
            }
            try
            {
                _repository.Officers.ApplyCurrentValues(officer);
                _repository.SaveChanges();
                return RedirectToAction("Details");
            }
            catch (Exception e)
            {
                ModelState.AddModelError(string.Empty, e);
                return View(officer);
            }
        }

        [Authorize]
        public ActionResult Details()
        {
            RankedOfficer officer = _repository.RankedOfficers.First(o => o.Email == HttpContext.User.Identity.Name);
            return View(officer);
        }
    }
}
